<template>
    <div class="page" ref="pageRef">
        <Breadcrumb :route="routes" />
        <div class="wb-container">
            <div class="mian-content">
                <div v-if="formIsShow">
                    <formPage :options="options" :fromList="fromList" @submit="handleBaseSubmit" @reset="handleResetFun" />
                </div>
                <div class="table-box">
                    <div class="actionBar">
                        <div>
                            <el-button class="blackBg" @click="RefreshClick"><i
                                    class="iconfont icon-shuaxin1"></i></el-button>
                        </div>
                        <div>
                            <el-button class="btnbg" ref="buttonRef" v-click-outside="onClickOutside"><i
                                    class="iconfont icon-caozuo-heng"></i></el-button>
                            <el-button class="btnbg" @click="tabelIsShow = !tabelIsShow"><i
                                    class="iconfont icon-qiehuan"></i></el-button>
                            <el-button class="btnbg" @click="excelClick"><i class="iconfont icon-daochu"></i></el-button>
                            <el-button class="btnbg" @click="formIsShow = !formIsShow">
                                <i class="iconfont icon-sousuo"></i>
                            </el-button>
                        </div>
                        <el-popover ref="popoverRef" :virtual-ref="buttonRef" trigger="click" virtual-triggering>
                            <div>
                                <el-checkbox-group v-model="checkedColumns" @change="watchCheckedColumns"
                                    class="checkbox-wrap">
                                    <el-checkbox size="large" style="display: block" v-for="item in checkBoxGroup"
                                        :key="item" :label="item" :value="item"></el-checkbox>
                                </el-checkbox-group>
                            </div>
                        </el-popover>
                    </div>
                    <el-table v-loading="loading" element-loading-text="加载数据..." :data="orderData"
                        style="width: 100%;height: 650px;" border
                        :header-cell-style="{ background: '#3CB731', color: '#fff', fontSize: '14px', height: '40px' }"
                        size="small" stripe v-if="tabelIsShow">
                        <template #empty>
                            <el-empty description="暂无数据！" />
                        </template>
                        <el-table-column prop="order_detail_goods" label="商品" align="center" width="360"
                            v-if="colData[0].istrue">
                            <template #default="{ row }">
                                <div v-for="(item, index) in row.order_detail_goods" :key="index">
                                    <div class="goodsInfo">
                                        <div class="goodsInfo-img">
                                            <el-image :src="item.image" />
                                        </div>
                                        <div style="margin-left:20px ;">{{ item.name }}</div>
                                        <div style="display: flex;">
                                            <div class="goodsName">￥<span>{{ item.pivot.price }}</span></div>
                                            <div class="goodsNum">x <span>{{ item.pivot.num }}</span></div>
                                        </div>
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="user.nickname" label="买家" align="center" width="200"
                            v-if="colData[1].istrue" />
                        <el-table-column prop="order_no" label="订单号" align="center" width="220" v-if="colData[2].istrue">
                            <template #default="{ row }">
                                <div class="orderNo">
                                    <div>{{ row.order_no }}</div>
                                    <button type="button" @click="copy(row.order_no)" class="copybtn">
                                        <i class="icow icow-order"></i>
                                    </button>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="device.name" label="设备名称" align="center" width="200"
                            v-if="colData[3].istrue" />
                        <el-table-column prop="create_time" label="下单时间" align="center" width="160"
                            v-if="colData[4].istrue" />
                        <el-table-column prop="amount" label="价格" align="center" v-if="colData[5].istrue" />
                        <el-table-column label="状态/维权" align="center" width="150" v-if="colData[6].istrue">
                            <template #default="{ row }">
                                <div class="state-tag">
                                    <text>
                                        <el-tag v-if="row.state == 'DOING'" type="warning">服务中</el-tag>
                                        <el-tag v-if="row.state == 'REVOKED'" type="info">已取消</el-tag>
                                        <el-tag v-if="row.state == 'DONE'" type="success">订单完成</el-tag>
                                        <el-tag v-if="row.state == 'REFUND'">退款</el-tag>
                                        <el-tag v-if="row.state == 'ERROR'" type="danger">异常订单</el-tag>
                                        <el-tag v-if="row.state == 'ERROR_HANDLE'" type="danger">异常订单已处理</el-tag>
                                        <el-tag v-if="row.state == 'DED_FAILED'" type="danger">扣款失败</el-tag>
                                    </text>
                                    <text>
                                        <el-tag v-if="row.order_protection?.type == '1'" type="danger">扣款错误</el-tag>
                                        <el-tag v-if="row.order_protection?.type == '2'" type="danger">未扣款</el-tag>
                                    </text>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="类型" align="center" v-if="colData[7].istrue">
                            <template #default="{ row }">
                                <div v-if="row.admin_user != null">
                                    <el-tag v-if="row.admin_user.type == 1">称重商品</el-tag>
                                    <el-tag v-if="row.admin_user.type == 2">视觉商品</el-tag>
                                </div>
                            </template>
                        </el-table-column>

                        <el-table-column prop="address" label="操作" align="center" min-width="180" fixed="right">
                            <template #default="{ row }">
                                <el-button type="primary" class="size btnColor" @click="orderEdit(row)"
                                    v-has="'orderDetali'">详情</el-button>
                                <el-button class="ProtectionBtnStyle" @click="orderProtection(row)"
                                    v-has="'orderStatus'">维权</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="orderCard">
                        <div v-for="(item, index) in orderData" :key="item.id"
                            :style="index % 2 !== 0 ? null : { 'backgroundColor': '#fcfafa' }" v-if="!tabelIsShow">
                            <div class="card-views">
                                <div>
                                    <el-row>
                                        <el-col :span="8">
                                            <div class="item-title">订单号</div>
                                        </el-col>
                                        <el-col :span="16">
                                            <div class="item-mian">{{ item.order_no }}</div>
                                        </el-col>
                                    </el-row>
                                </div>
                                <div>
                                    <el-row>
                                        <el-col :span="8">
                                            <div class="item-title">订单商品</div>
                                        </el-col>
                                        <el-col :span="16">
                                            <div>
                                                <div v-for="(it, index) in item.order_detail_goods" :key="index">
                                                    <div class="goodsInfo">
                                                        <div class="goodsInfo-img">
                                                            <el-image :src="it.image" />
                                                        </div>
                                                        <div style="margin-left:20px ;">{{ it.name }}</div>
                                                        <div style="display: flex;">
                                                            <div class="goodsName">￥<span>{{ it.pivot.price }}</span></div>
                                                            <div class="goodsNum">x <span>{{ it.pivot.num }}</span></div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </el-col>
                                    </el-row>
                                </div>
                                <div>
                                    <el-row>
                                        <el-col :span="8">
                                            <div class="item-title">用户名</div>
                                        </el-col>
                                        <el-col :span="16">
                                            <div>{{ item.user.nickname }}</div>
                                        </el-col>
                                    </el-row>
                                </div>

                                <div>
                                    <el-row>
                                        <el-col :span="8">
                                            <div class="item-title">设备名称</div>
                                        </el-col>
                                        <el-col :span="16">
                                            <div>{{ item.device.name }}</div>
                                        </el-col>
                                    </el-row>
                                </div>
                                <div>
                                    <el-row>
                                        <el-col :span="8">
                                            <div class="item-title">订单开始时间</div>
                                        </el-col>
                                        <el-col :span="16">
                                            <div>{{ item.create_time }}</div>
                                        </el-col>
                                    </el-row>
                                </div>
                                <div>
                                    <el-row>
                                        <el-col :span="8">
                                            <div class="item-title">金额</div>
                                        </el-col>
                                        <el-col :span="16">
                                            <span class="redColor cardPrice">￥{{ item.amount }}</span>
                                        </el-col>
                                    </el-row>
                                </div>
                                <div>
                                    <el-row>
                                        <el-col :span="8">
                                            <div class="item-title">状态</div>
                                        </el-col>
                                        <el-col :span="16">
                                            <text>
                                                <el-tag v-if="item.state == 'DOING'" type="warning">服务中</el-tag>
                                                <el-tag v-if="item.state == 'REVOKED'" type="info">已取消</el-tag>
                                                <el-tag v-if="item.state == 'DONE'" type="success">订单完成</el-tag>
                                                <el-tag v-if="item.state == 'REFUND'">退款</el-tag>
                                                <el-tag v-if="item.state == 'ERROR'" type="danger">异常订单</el-tag>
                                                <el-tag v-if="item.state == 'ERROR_HANDLE'" type="danger">异常订单已处理</el-tag>
                                                <el-tag v-if="item.state == 'DED_FAILED'" type="danger">扣款失败</el-tag>
                                            </text>
                                            <text>
                                                <el-tag v-if="item.order_protection?.type == '1'"
                                                    type="danger">扣款错误</el-tag>
                                                <el-tag v-if="item.order_protection?.type == '2'" type="danger">未扣款</el-tag>
                                            </text>
                                        </el-col>
                                    </el-row>
                                </div>
                                <div>
                                    <el-row>
                                        <el-col :span="8">
                                            <div class="item-title">商家类型</div>
                                        </el-col>
                                        <el-col :span="16">
                                            <div v-if="item.admin_user != null">
                                                <el-tag v-if="item.admin_user.type == 1">称重商品</el-tag>
                                                <el-tag v-if="item.admin_user.type == 2">视觉商品</el-tag>
                                            </div>
                                        </el-col>
                                    </el-row>
                                </div>
                                <div>
                                    <el-row>
                                        <el-col :span="8">
                                            <div class="item-title">操作</div>
                                        </el-col>
                                        <el-col :span="16">
                                            <el-button type="primary" class="size btnColor" @click="orderEdit(item)"
                                                v-has="'orderDetali'">详情</el-button>
                                            <el-button class="ProtectionBtnStyle" @click="orderProtection(item)"
                                                v-has="'orderStatus'">维权</el-button>
                                        </el-col>
                                    </el-row>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="demo-pagination-block">
                    <div style="margin-right: 30px;">金额：<text style="color: red;">￥{{ AllPrice }}</text>
                    </div>
                    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                        :page-sizes="[10, 15, 20, 25]" :small="small" :disabled="disabled" :background="background"
                        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" />
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { useRoute } from "vue-router";
import Breadcrumb from '@/components/nav-header'
import formPage from "@/components/form";
import { ref, onBeforeMount, onMounted, computed, reactive, getCurrentInstance, unref } from 'vue'
import { orderList } from '@/api/order'
import { DeviceList } from '@/api/Device'
import { formatDate, changeTableHead } from '@/utlis/index'
import * as xlsx from 'xlsx'
import _ from 'lodash'
import router from '@/router'
import { ElMessage } from 'element-plus'
import { ClickOutside as vClickOutside } from 'element-plus'
import { useStore } from 'vuex'

const store = useStore()
const route = useRoute()
const routes = ref()
const pageRef = ref()
const formIsShow = ref(false)
const tabelIsShow = ref(true)
const { proxy } = getCurrentInstance()
const fromSearch = ref({})
const params = ref({})
//请求回来的原数据
const orderData = ref([
    {
        admin_user: {
            type: ''
        },
        admin_user_id: '',
        amount: 0,
        create_time: '',
        end_time: '',
        id: '',
        order_detail_goods: [],
        order_no: '',
        reason: '',
        refund_amount: '',
        state: '',
        state_description: '',
        user: '',
        user_id: '',
        order_protection: {}

    }
])
const loading = ref(true)
const excalData = ref([])
const buttonRef = ref()
const popoverRef = ref()
var reload = ref();
const checkBoxGroup = ref(
    ["商品", "用户", "订单号", "设备名称", "下单时间", "价格", "状态/维权", "类型"]
)
// 当前选中的多选框，代表当前展示的列
const checkedColumns = ref(
    ["商品", "用户", "订单号", "设备名称", "下单时间", "价格", "状态/维权", "类型"]
)
// colData中列出表格中的每一列，默认都展示
const colData = reactive([
    { title: "商品", istrue: true },
    { title: "用户", istrue: true },
    { title: "订单号", istrue: true },
    { title: "设备名称", istrue: true },
    { title: "下单时间", istrue: true },
    { title: "价格", istrue: true },
    { title: "状态/维权", istrue: true },
    { title: "类型", istrue: true },
])
//form表单的数据
const fromList = reactive([
    {
        label: '用户ID',
        type: 'input',
        field: "user_id",
        placeholder: "输入用户id",
    },
    {
        label: '订单号',
        type: 'input',
        field: "order_no",
        placeholder: "输入订单号",
    },
    {
        label: '时间',
        type: 'datetimerange ',
        field: "datetimerange",
        start_placeholder: '选择开始时间',
        end_placeholder: '选择结束时间',
        placeholder: "选择时间范围",
    },
    {
        label: '状态',
        type: 'select',
        field: "state",
        placeholder: "选择订单状态",
        option: [
            {

                label: '',
                value: ''
            },
            {
                label: '服务中',
                value: 'DOING'
            },
            {
                label: '订单完成',
                value: 'DONE'
            },
            {
                label: '退款',
                value: 'REFUND'
            },
            {
                label: '已取消',
                value: 'REVOKED'
            },
            {
                label: '异常订单',
                value: 'ERROR'
            },
            {
                label: '已处理的异常订单',
                value: 'ERROR_HANDLE'
            },
            {
                label: '扣款失败',
                value: 'DED_FAILED'
            }
        ]
    },
    {
        label: '设备名称',
        type: 'select',
        field: "device_id",
        placeholder: "选择设备",
    }
])
const options = reactive({
    showResetButton: true,
})
const device = ref([])
onBeforeMount(async () => {
    await DeviceList().then(s => {
        const { code, data } = s
        if (code == 200) {
            for (let i = 0; i < data.data.length; i++) {
                device.value.push({
                    label: data.data[i].name,
                    value: data.data[i].id
                })
            }
            console.log(device.value, '过滤后的数据');
            fromList.forEach(item => {
                if (item.label === '设备名称') {
                    item.option = device.value
                }
            })
            console.log(device.value, '设备名称');
        }
    })
})
const handleBaseSubmit = (model) => {
    if (model.datetimerange) {
        let start_time = formatDate(model?.datetimerange[0])
        let end_time = formatDate(model?.datetimerange[1])
        model.start_time = start_time
        model.end_time = end_time
    }
    fromSearch.value = model
    getOrderList()
}
const handleResetFun = (value) => {
    delete value.start_time
    delete value.end_time
    fromSearch.value = value
    getOrderList()
}

// 监听checkedColumns的变化，当checkedColumns发生变化时，重新渲染表格
const watchCheckedColumns = () => {
    // 遍历colData，将colData中的istrue属性设置为false
    colData.forEach((item) => {
        item.istrue = false
    })
    // 遍历checkedColumns，将checkedColumns中的值在colData中找到对应的列，将istrue属性设置为true
    checkedColumns.value.forEach((item) => {
        colData.forEach((col) => {
            if (item === col.title) {
                col.istrue = true
            }
        })
    })
    // 重新渲染表格
    reload.value = Math.random()
}
const onClickOutside = () => {
    unref(popoverRef).popperRef?.delayHide?.()
}
const RefreshClick = () => {
    getOrderList(form)
}

const shortcuts = [
    {
        text: '一周',
        value: () => {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            return date
        },
    },
    {
        text: '一个月',
        value: () => {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 30)
            return date
        },
    },
    {
        text: '三个月',
        value: () => {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 90)
            return date
        },
    },
]
const devcieData = ref([])
//分页器的数据
const currentPage = ref(1)
const pageSize = ref(15)
const small = ref(false)
const background = ref(true)
const disabled = ref(false)
const total = ref(0)
const AllPrice = ref('')

const getOrderList = async () => {
    params.value = _.cloneDeep(fromSearch.value)
    if (params.value) {
        delete params.value.datetimerange
    }
    const data = await orderList({ ...params.value, limit: pageSize.value, page: currentPage.value }).then(res => {
        const { code, data } = res
        loading.value = false
        if (code == 200) {
            orderData.value = data.data
            total.value = data.total || 0
            AllPrice.value = data.sum_amount
        }

    }).catch((err) => {
        loading.value = false
    })
}
onMounted(() => {
    routes.value = route.matched
    const historyParam = history.state
    if (historyParam.param) {
        form.user_id = historyParam.param
        getOrderList()
    } else {
        getOrderList()
    }

})
const copy = (it) => {
    proxy.$copyText(it).then(
        (success) => {
            ElMessage.success('复制成功')
        },
        (err) => {
            ElMessage.error('复制失败')

        })
}
//分页的方法
const handleSizeChange = (val) => {
    pageSize.value = val
    getOrderList()
}
const handleCurrentChange = (value) => {
    currentPage.value = value
    getOrderList()
}
computed(orderData, () => {
    return orderData.value.slice(
        (this.currentPage - 1) * this.pageSize,
        this.currentPage * this.pageSize,
    )
})
const orderEdit = (row) => {
    console.log(row, '订单数据');
    let params = {
        id: row.id,
        type: row.admin_user.type
    }
    router.push({
        name: 'orderEdit',
        state: { params }
    })
}
const orderProtection = (item) => {
    let orderId = JSON.parse(JSON.stringify(item.id))
    router.push({
        name: 'status',
        state: { orderId }
    })
}
//导出excel表格
const excelClick = async () => {
    let page = total.value
    params.value = _.cloneDeep(fromSearch.value)
    if (params.value) {
        delete params.value.datetimerange
    }
    await orderList({ ...params.value, limit: page, page: currentPage.value }).then(res => {
        const { data } = res
        excalData.value = data.data
        console.log(excalData.value, '导出的数据');
    })
    let fileNameObj = {
        order_no: '订单号',
        nickname: '用户昵称',
        amount: '商品小计',
        state: '状态',
        user_id: '用户ID',
        admin_user_id: '管理员ID',
        create_time: '订单开始时间',
        end_time: '订单结束时间',
        refund_amount: '订单金额',
        state_description: '类型描述',
        id: 'id',
        head_img: '用户头像',
        // name: '商品名称',
        // price: '商品单价',
        // num: '商品数量'
    }
    var deep = _.cloneDeep(excalData.value);
    let orderItem = [...deep]
    let userList = {} //用户的数据
    let orderDetaliGoods = {} //订单商品的数据
    let exportData = orderItem.map(it => {
        userList = it.user
        orderDetaliGoods = it.order_detail_goods
        const filterarr = ["user", 'order_detail_goods', 'collection'];
        for (let key in it) {
            filterarr.find((item) => {
                if (key === item) {
                    delete it[item];
                }
            });
        }
        let orderGoods = orderDetaliGoods.map(it => {
            delete it.pivot.cameraId
            let pivot = it.pivot
            return {
                id: it.id,
                image: it.image,
                name: it.name,
                ...pivot
            }
        })
        let exportGoods = [...orderGoods][0]
        let excelList = { ...it, ...userList, ...exportGoods }
        return excelList
    })
    // return
    let goodsExcelData = changeTableHead(exportData, fileNameObj)
    // // 创建工作表
    const data = xlsx.utils.json_to_sheet(goodsExcelData);
    // 创建工作簿
    const wb = xlsx.utils.book_new();
    //表格文本居中
    data['!cols'] = [{
        wpx: 80
    }, {
        wpx: 100
    },
    {
        wpx: 200
    },
    {
        wpx: 100
    },
    {
        wpx: 100
    },
    {
        wpx: 100
    },
    {
        wpx: 150
    },
    {
        wpx: 150
    },
    {
        wpx: 100
    },
    {
        wpx: 100
    },
    {
        wpx: 200
    },
    {
        wpx: 500
    },
    {
        wpx: 100
    },
    {
        wpx: 100
    },
    ]
    let memberListName = '订单列表数据'
    let fileName = 'Sheet3'
    // 将工作表放入工作簿中  
    xlsx.utils.book_append_sheet(wb, data, memberListName);
    // 生成文件并下载
    xlsx.writeFile(wb, `${fileName}.xlsx`);
    pageSize.value = pageSize.value
    getOrderList()
}

</script>

<style lang="less" scoped>
.Search-box {
    padding: 0;
    border-bottom: 1px solid #f0f0f0;
}

.actionBar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
}

.actionBarbg {
    background-color: #3CB731;
    color: #fff;
}

.redColor {
    background-color: #f75444;
    color: #ffffff;
}

.iconfont {
    font-size: 12px;
}

.btnbg {
    background-color: #f0f0f0;
}

.blackBg {
    background-color: #24303c;
    color: #fff;

    :active {
        background-color: #333333;
        color: #f0f0f0;
    }
}

.search-btn {
    margin-left: 80px;
}

:deep(.el-date-editor.el-input) {
    width: 300px;
}

:deep(.el-date-editor.el-input .el-input__wrapper) {
    width: 300px;
}


.demo-pagination-block {
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    align-items: center;
}

.demo-pagination-block+.demo-pagination-block {
    margin-top: 10px;
}

.demo-pagination-block .demonstration {
    margin-bottom: 16px;
}

.goodsInfo {
    display: flex;
    justify-content: space-between;
    margin: 0 5px 5px 0px;
    align-items: center;

    .goodsInfo-img {
        width: 50px;
        height: 50px;
        margin: 10px;

        .el-image {
            width: 100%;
            height: 100%;
        }
    }
}

.state-tag {
    padding: 20px;
    display: flex;
    justify-content: center;
    align-items: center;

    text {
        margin: 2px;
    }
}

.selectstyle:hover {
    background-color: #409eff;
    color: #fff;
}

.goodsName {
    margin-left: 10px;
    font-size: 12px;
    color: #333333;
    font-family: '微软雅黑';
}

.goodsNum {
    margin-left: 20px;
    font-size: 12px;
    color: #333333;
    font-family: '微软雅黑';
}

.orderNo {
    display: flex;
    justify-content: center;
    align-items: center;

    button {
        margin-left: 5px;

        i {
            color: #fff;
            background-color: #c8c8c8;
        }
    }
}

.copybtn:hover {
    cursor: pointer;
}

.dataImg {
    cursor: pointer;
    margin-left: 5px;
}

.el-dialog__header {
    text-align: center;
}

.ProtectionBtnStyle {
    background-color: #d4b106;
    color: #fff;
}


:deep(.el-dialog) {
    header {
        background: rgb(68, 171, 247);
        margin-right: 0;

        .el-dialog__title {
            color: #fff;
        }

        .el-dialog__headerbtn i {
            color: #fff;
        }
    }
}

:deep(.el-button) {
    padding: 2px 6px;
    letter-spacing: 2px;
    font-size: 12px;
}
</style>
